//
//  MainViewController.m
//  LearningFMDB
//
//  Created by dihuijun on 17/9/13.
//  Copyright © 2017年 Cycle. All rights reserved.
//

#import "MainViewController.h"
#import "SQLHelper.h"
#import "Person.h"
#import "Car.h"
//所有用户和车   （车库）
#import "AllPersonAndCarsViewController.h"
//点击MainViewController每一行Cell进去为用户添加车
#import "PersonAddCarViewController.h"

@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *_picArray;
    NSIndexPath *_currentIndexPath;
}
/**   表格   */
@property (nonatomic, strong) UITableView *tableView;
/**   数据源   */
@property (nonatomic, strong) NSMutableArray<Person *>*datasource;
@end

@implementation MainViewController
/**   数据源   */
- (NSMutableArray *)datasource{
    if(!_datasource){
        _datasource = [NSMutableArray array];
    }
    return _datasource;
}
/**   表格   */
- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取数据库数据
    self.datasource = [[SQLHelper sharedSQLHelper]getAllPerson];
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    _picArray = [NSMutableArray arrayWithObjects:@"p1.png",@"p2.jpg", nil];
    //1.设置导航栏
    [self setupNavgation];
    //2.表格相关数据
    [self setupTableview];
    
    
    
    
}

#pragma mark --- 1.设置导航栏
- (void)setupNavgation{
    self.navigationItem.title = @"数据库相关";
    self.view.backgroundColor = [UIColor whiteColor];
    //左边车库
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"车库" style:UIBarButtonItemStyleDone target:self action:@selector(ClickAllCars)];
    //右边添加person
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(ClickAddPerson)];
    
    
    
}
/**
 *  左边车库
 */
- (void)ClickAllCars{
    AllPersonAndCarsViewController *allVC = [[AllPersonAndCarsViewController alloc]init];
    [self.navigationController pushViewController:allVC animated:YES];
}
/**
 *  右边添加person
 */
- (void)ClickAddPerson{
    
    
    
    //姓名
    int nameRandom = arc4random_uniform(1000);
    NSString *name = [NSString stringWithFormat:@"person_%d 号",nameRandom];
    //头像
    NSInteger headRandowIndex = arc4random_uniform(_picArray.count);
    UIImage *img = [UIImage imageNamed:_picArray[headRandowIndex]];
    //年龄
    NSInteger ageRandom = arc4random_uniform(100)+1;
    NSInteger age = ageRandom;
    
    //创建person类
    Person *person       = [Person new];
    person.name          = name;
    person.age           = age;
    person.headImageData = UIImagePNGRepresentation(img);
    //添加到数据库
    [[SQLHelper sharedSQLHelper]addPerson:person];
    //添加到数据源
    self.datasource = [[SQLHelper sharedSQLHelper]getAllPerson];
    //刷新表格
    [self.tableView reloadData];
}
#pragma mark ---- 2.表格相关数据
- (void)setupTableview{
    //1.add table
    [self.view addSubview:self.tableView];
    __weak typeof(self) wself = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //添加到数据源
        [wself.datasource removeAllObjects];
        wself.datasource = [[SQLHelper sharedSQLHelper]getAllPerson];
        //刷新表格
        [wself.tableView reloadData];
        [wself.tableView.mj_header endRefreshing];
    }];
    
    
    
    
    
    
}


#pragma mark --- <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"personCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    _currentIndexPath = indexPath;
    //创建person
    Person *person = self.datasource[indexPath.row];
    if (person.number == 0) {
        cell.textLabel.text = person.name;
    }else{
        cell.textLabel.text = [NSString stringWithFormat:@"%@(第%ld次更新)",person.name,person.number];
    }
    cell.detailTextLabel.text = [NSString stringWithFormat:@"age : %ld",person.age];
    cell.imageView.image = [UIImage imageWithData:person.headImageData];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    cell.imageView.userInteractionEnabled = YES;
    [cell.imageView addGestureRecognizer:tap];
    
    return cell;
}
///测试修改头像
- (void)tap{
    //NSLog(@"%zd---%zd",_currentIndexPath.section,_currentIndexPath.row);
    Person *person = self.datasource[_currentIndexPath.row];
    NSLog(@"%zd---%zd----%@",_currentIndexPath.section,_currentIndexPath.row,person.ID);
    NSInteger headRandowIndex = arc4random_uniform(_picArray.count);
    UIImage *img = [UIImage imageNamed:_picArray[headRandowIndex]];
    person.headImageData = UIImagePNGRepresentation(img);
    [[SQLHelper sharedSQLHelper] updatePersonHeadImage:person];
    [self.tableView reloadRowsAtIndexPaths:@[_currentIndexPath] withRowAnimation:UITableViewRowAnimationRight];
}
/**
 *  设置删除按钮
 */
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //获取需要删除的模型
        Person *person = self.datasource[indexPath.row];
        //执行SQL
        [[SQLHelper sharedSQLHelper]deletePerson:person];
        ///详情里面有他车车，所以需要删掉
        [[SQLHelper sharedSQLHelper]deleteAllCarsFromPerson:person];
        
        //重新获取数据
        self.datasource = [[SQLHelper sharedSQLHelper]getAllPerson];
        //刷新表格
        [self.tableView reloadData];
    }
}
/**
 * 点击cell
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonAddCarViewController *addVC = [[PersonAddCarViewController alloc]init];
    addVC.person = self.datasource[indexPath.row];
    [self.navigationController pushViewController:addVC animated:YES];
}




@end
